package com.xykj.enterprise.wechat.ext.api.identity;

import com.xykj.enterprise.wechat.ext.service.identity.PreAuthCodeUtil;
import com.xykj.enterprise.wechat.ext.service.identity.SuiteAccessTokenUtil;
import com.xykj.enterprise.wechat.bean.ext.identity.PreAuthCode;
import com.xykj.enterprise.wechat.bean.ext.identity.SuiteAccessToken;
import com.xykj.enterprise.wechat.util.biz.BizException;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Parameter;
import com.ydn.appserver.annotations.Type;
import com.ydn.simplecache.SimpleCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author zhouxu
 * @create 2021-03-29 16:17
 */
@Slf4j
@Function(description = "获取预授权码", parameters = {
        @Parameter(name = "suite_id", type = Type.String, description = "以ww或wx开头应用id（对应于旧的以tj开头的套件id", required = true),
        @Parameter(name = "suite_secret", type = Type.String, description = "应用secret", required = true),
        @Parameter(name = "suite_ticket", type = Type.String, description = "企业微信后台推送的ticket", required = true),
})
@Component
public class GetPreAuthCode implements Action {

    @Autowired
    private SimpleCache simpleCache;

    @Override
    public Response execute(Request request) throws Exception {
        String suiteId = request.getString("suite_id");
        String suiteSecret = request.getString("suite_secret");
        String suiteTicket = request.getString("suite_ticket");
        log.debug("suiteId:{},suiteSecret:{},suiteTicket:{}", suiteId, suiteSecret, suiteTicket);
        try {
            SuiteAccessToken suiteAccessToken = SuiteAccessTokenUtil.get(simpleCache, suiteId, suiteSecret, suiteTicket);
            PreAuthCode preAuthCode = PreAuthCodeUtil.get(suiteAccessToken.getSuite_access_token());

            return Response.success().put("data", preAuthCode);
        } catch (BizException biz) {
            log.error(biz.getErrMsg(), biz.getErrCode());
            return Response.fail(biz.getMessage(), biz.getErrCode());
        } catch (Exception e) {
            log.error("", e);
            return Response.fail(e);
        }

    }
}
